//
//  HPSwiperService.m
//  HPZZTong
//
//  Created by wenjun on 14-5-6.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPSwiperService.h"
#import "POSProcess.h"
#import "SwiperDefine.h" // marco add

static HPSwiperService * swiperService = nil;
// private method for HPSwiperService.
@interface POSProcess()
- (void)start;
- (void)icQuestInputPin;
@end

@interface HPSwiperService()
@property (readonly,nonatomic) EncyptType encyptType;
@property (strong,nonatomic) NSString * swiperFactor;
@property (strong, nonatomic) SwiperComplete complete;
@property (nonatomic)SwiperType swiperType;
@end

@implementation HPSwiperService

- (id)init
{
    self = [super init];
    _swiperType = SwiperTypeNone;
    return self;
}

-(void)dealloc
{
    self.currentSwiper = nil;
    self.complete = nil;
}

- (void)distorySwiper
{
    self.currentSwiper = nil;
    _csnStatus = CSNStatusNone;
    _encyptType = EncyptTypeNone;
    _swiperType = SwiperTypeNone;
    _swiperFactor = nil;
}

-(void)setCurrentSwiper:(HPBaseSwiper *)currentSwiper
{
    if (_currentSwiper != currentSwiper)
    {
        if (_currentSwiper)
        {
            [_currentSwiper disconnect];
            [_currentSwiper releaseInstance];
            [_currentSwiper removeObserver:self forKeyPath:@"connectState"];
        }
        _currentSwiper = currentSwiper;
        [_currentSwiper addObserver:self forKeyPath:@"connectState" options:NSKeyValueObservingOptionNew context:nil];
        [_currentSwiper activeInstance];
    }
}

- (void)swiperSelectSucess:(NSNotification*)note
{
    if (self.complete)
        ExecuteSwiperBlock(self.complete, [HPSwiperResult successResult:self.csn]);
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"connectState"])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self connectStateChanged:[object connectState] swiper:object];
        });
    }
}

- (void)connectStateChanged:(SwiperState)connectState swiper:(HPBaseSwiper *)swiper
{
    SwiperState state = swiper.connectState;
    if (connectState == SwiperStateDectedDevice)
    {
        if (!self.currentSwiper || self.currentSwiper == swiper)
            [self checkAndConnectSwiper:nil];
    }
    if (swiper == self.currentSwiper)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:SwiperStateChangeNotificationKey
                                                            object:[NSNumber numberWithInteger:state]];
        if (connectState == SwiperStateNoDeviceDected || connectState == SwiperStateConnectFailed)
        {
            [self distorySwiper];
        }
        else if (connectState ==  SwiperStateConnected)
        {
//            if (![CSNValidator isRunning]) // marco changed
//                [CSNValidator checkCSNStatus:nil autoTip:YES];
        }
    }
}

- (void)selectSwiperAndGetCsn:(SwiperComplete)block isShow:(BOOL)show
__attribute__((deprecated("HPSwipeContext responsablity to instance an swiper instnce. more detail watch:'HPSwipeContext->setSelectedSwiperDescription:' method")))
{
    return;
}

- (void)changeSwiperType:(SwiperType)swiperType
__attribute__((deprecated("instead of HPSwipeContext::setSelectedSwiperDescription")))
{
    return;
}

- (void)checkAndConnectSwiper:(SwiperComplete)complete
{
    if (!self.currentSwiper.isConnected)
        [_currentSwiper getKSN:complete];
    else
        ExecuteSwiperBlock(complete, [HPSwiperResult successResult:self.currentSwiper.ksn]);
}

- (SwiperComplete)addAction:(NSString *)action toCallBack:(SwiperComplete)complete
{
    if (complete)
    {
        SwiperComplete actionComplete = ^(HPSwiperResult * swiperResult)
        {
            [swiperResult setProperty:action forKey:@"action"];
            complete(swiperResult);
        };
        return actionComplete;
    }
    return nil;
}

- (void)doSwiper:(SwiperComplete)block
{
    block = [self addAction:SWIPER_SWIPE toCallBack:block];
    [self.currentSwiper swipe:30*1000 factor:_swiperFactor complete:block];
}

- (void)doEncyptPin:(NSString *)pin complete:(SwiperComplete)complete
{
    complete = [self addAction:SWIPER_INPUT_PWD toCallBack:complete];
    [self.currentSwiper encryptPin:pin factor:_swiperFactor complete:complete];
}

- (void)doInputICPin:(NSString *)pin complete:(SwiperComplete)complete {}

- (void)doSelectApp:(NSArray*)type complete:(SwiperComplete)complete
{
    [self.currentSwiper selectApp:type time:5 factor:_swiperFactor complete:nil];
}

- (void)doInputPwdWithAmount:(NSString *)amount complete:(SwiperComplete)complete
{
    complete = [self addAction:SWIPER_INPUT_PWD toCallBack:complete];
    [_currentSwiper inputPwd:60 amount:amount factor:_swiperFactor complete:complete];
}

- (void)doMac:(NSString*)data complete:(SwiperComplete)complete
{
    complete = [self addAction:SWIPER_MAC toCallBack:complete];
    [self.currentSwiper encryptMac:data factor:_swiperFactor complete:complete];
}

- (BOOL)isCMBCSwiper:(NSString*)ksn
{
    BOOL isCMBC = ksn.length > 4 ;
    if (isCMBC)
        isCMBC = [[ksn substringToIndex:4].uppercaseString isEqualToString:@"CMBC"];
    return isCMBC;
}

- (NSString *)resetFactor
{
    _swiperFactor = [NSString stringWithFormat:@"%@80", [self getNowDateTime_CopyFromUtilityForExtractSwiperModule]];
    return _swiperFactor;
}

-(NSString*)getNowDateTime_CopyFromUtilityForExtractSwiperModule
{
    NSDate* now = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString* nowStr = [formatter stringFromDate:now];
    return nowStr;
}

- (NSString*)getFatorTime
{
    if (!_swiperFactor)
        [self resetFactor];
    return [_swiperFactor substringToIndex:(_swiperFactor.length -2)];
}

- (NSString *)csn { return self.currentSwiper.ksn; }
- (void)setCsnStatus:(CSNStatus)csnStatus { _csnStatus = csnStatus; }

- (BOOL)cancelSwiperOperation
{
    BOOL needCancel = [_currentSwiper hasOperation];
    if (needCancel)
        [_currentSwiper cancelSwiperOperation];
    return needCancel;
}

- (void)startProcess:(POSProcess *)process
{
    _currentProcess = process;
    _currentProcess.currentSwiper = _currentSwiper;
    [process start];
}

- (NSString *)icQuestInputPin
{
    dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
    dispatch_after(delayInNanoSeconds, dispatch_get_main_queue(), ^{
        [_currentProcess icQuestInputPin];
    });
    return _currentProcess.plainAmount;
}

-(SwiperState)swiperConnectState
{
    if(!self.currentSwiper)
        return SwiperStateNoDeviceDected;
    return self.currentSwiper.connectState;
}

@end
